<?php
/**
 * 美食
 *
 * @copyright  Copyright (c) 2015-2025 NcPHP Inc. (http://www.ncphp.com)
 * @license    http://www.ncphp.com/
 * @link       http://www.ncphp.com/
 * @author	   NcPHP Team
 * @since      File available since Release v2.1
 */
defined('InNcPHP') or exit('Access Invalid!');
class foodControl  extends  SystemControl{

    private $links = array(
        array('url'=>'act=food&op=index','lang'=>'nc_manage'),
        array('url'=>'act=food&op=add','lang'=>'nc_new'),
    );
    public function __construct()
    {
        parent::__construct();
        Language::read('ticket');
        Tpl::setDir('food');
    }

    //搜索列表页
    public function indexOp()
    {
        $food_model = Model('food');
        $merchant_model = Model('member_merchant');
        $category_model = Model('ticket_category');
        //查询条件
        $condition =array();
        if(isset($_GET['search_title']) && $_GET['search_title']){
            $condition['fd_title'] = array('like','%'.$_GET['search_title'].'%');
        }
        if (isset($_GET['search_state']) && is_numeric($_GET['search_state'])) {
            $condition['fd_status'] = intval($_GET['search_state']);
        }
        $merchant_id = intval($this->admin_info['merchant_id']);
        if($merchant_id>0){
            $condition['merchant_id'] = $merchant_id;
        }else{
            if (isset($_GET['search_merchant']) && is_numeric($_GET['search_merchant'])) {
                $condition['merchant_id'] = intval($_GET['search_merchant']);
            }
        }
        if (isset($_GET['search_cate1']) && is_numeric($_GET['search_cate1'])) {
            $condition['cate_id'] = intval($_GET['search_cate1']);
        }
        if(isset($_GET['fd_type']) && is_numeric($_GET['fd_type'])){
            $condition['fd_type'] = intval($_GET['fd_type']);
        }

        $day = getgpc('day');
        if($day=='today'){
            $time_from = $time_to = strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d"),date("Y")))) ;
            $time_to = $time_to + 86400;
            $condition['fd_add_time'] = array('between',array($time_from,$time_to));
        }


        $foods = $food_model->getFoodListPage($condition, '*', 10);
        $cates = $category_model->getCategoryList();
        foreach($foods as $key => $v){
            $foods[$key]['shop_name'] = $merchant_model->getfby_merchant_id($v['merchant_id'], 'mc_shop_name');
            //$foods[$key]['fd_thumb'] = UPLOAD . 'food/' . $v['fd_thumb'];
            $foods[$key]['fd_thumb'] = get_thumb($v['fd_thumb'],FOOD_MARK,240);
            foreach ($cates as $cate) {
                if ($v['cate_id'] == $cate['tc_id']) {
                    $foods[$key]['cate_id'] = $cate['tc_name'];
                } else if ($v['tk_cate2'] == $cate['tc_id']) {
                    $foods[$key]['tk_cate2'] = $cate['tc_name'];
                }
            }
        }
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }

        $cate1 = $category_model->getCategoryList(array('tc_pid'=>FOOD_MARK,'is_del'=>0));//门票底下所有分类
        Tpl::output('search', $_GET);
        Tpl::output('cate1', $cate1);
        Tpl::output('foods',$foods);
        Tpl::output('merchants',$merchants);
        Tpl::output('page',$food_model->showpage());
        Tpl::output('top_link',$this->sublink($this->links,'index'));
        Tpl::showpage('food.index');
    }

    //添加页
    public function addOp(){
        $ticket_category = Model('ticket_category');
        $area_model = Model('area');
        /* @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        if(chksubmit()){
            $food_model = Model('food');
            $insert_array = array();
            $insert_array['fd_title'] = trim($_POST['title']);
            $insert_array['merchant_id'] = intval($this->admin_info['merchant_id'])>0?intval($this->admin_info['merchant_id']):intval($_POST['merchant_id']);
            $insert_array['cate_id'] = intval($_POST['cate1']);
            $insert_array['fd_content'] = $_POST['content'];//菜品介绍
            $insert_array['fd_tips']    = $_POST['content1'];//购买需知
            $insert_array['fd_subtitle'] = $_POST['fd_subtitle'];//副标题
            $insert_array['cost_price']  = $_POST['cost_price_'];//成本价
            $insert_array['is_purchase'] = intval(getgpc('is_purchase'));//是否可购买
            $open_spec = getgpc("open_spec");
            $obj_validate = new Validate();
            $fd_type = $_POST['food_type'];
            if($fd_type==1){
                $open_spec = 0 ;
            }
            $insert_array['fd_type'] = $_POST['food_type'];
            if(!$open_spec){
                $obj_validate->validateparam = array(
                    array("input"=>$_POST["show_price"], "require"=>"true",  "message"=>'原价不能为空'),
                    array("input"=>$_POST["price"], "require"=>"true", 'min'=>0,  "message"=>'价格不能为空'),
                    array("input"=>$_POST["stock"], "require"=>"true",  "message"=>'库存不能为空'),
                    array("input"=>$_POST["label"], "require"=>"true",  "message"=>'标签不能为空'),
                );
                $error = $obj_validate->validate();
                if ($error != ''){
                    showMessage($error);
                }
                $insert_array['fd_market_price'] = floatval($_POST['show_price']);
                $insert_array['price'] = floatval($_POST['price']);
                $insert_array['stock'] = $_POST['stock'];
                $insert_array['label'] = $_POST['label'];
            }
            $insert_array['open_spec'] = $open_spec;
            $insert_array['fd_add_time'] = time();
            $insert_array['fd_update_time'] = time();
            $insert_array['deduction'] = $_POST['deduction'];
            $insert_array['sales'] = intval($_POST['sales']);
            //查询该商家的市ID
            $store_location = trim($_POST['store_location']);
            $store_gps = explode(',', $store_location);
            $insert_array['food_lat']   = $store_gps[1];
            $insert_array['food_lng']   = $store_gps[0];
            $insert_array['fd_province_id'] = $_POST['province_id'];
            $insert_array['fd_city_id'] =$_POST['city_id'];
            $insert_array['fd_area_id'] =$_POST['area_id'];
            $insert_array['fd_addr'] = $_POST['addr'];
            $insert_array['fd_city_name'] = $area_model->getfby_area_id($_POST['city_id'],'name');
            $insert_array['fd_full_addr'] = implode('',array(
                $area_model->getfby_area_id(intval($_POST['province_id']),'name'),
                $insert_array['fd_city_name'],
                $area_model->getfby_area_id(intval($_POST['area_id']),'name'),
                $_POST['addr']
            ));
            $upload = new UploadFile();
            $upload->set('default_dir','food/'.$upload->getSysSetPath());
            $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
            $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
            $upload->set('thumb_ext', GOODS_IMAGES_EXT);
            $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
            //封面图片
            $result = $upload->upfile('thumb');
            if($result){
                $insert_array['fd_thumb'] = $upload->getSysSetPath() . $upload->file_name;
            } else {
                //图片上传失败
                $this->log('美食封面图上传失败'.'[标题:'.$_POST['title'].']',0);
                showMessage(L('nc_common_save_fail').$upload->error);
            }
            if($open_spec){
                $insert_array['price'] = min($_POST['spec_price']); //提取规格中的最低价 插入美食表中
                $key = array_search(min($_POST['spec_price']),$_POST['spec_price']);
                $insert_array['fd_market_price'] = $_POST['spec_market_price'][$key]; //提取规格中最低价的展示价 插入美食表中
            }
            $result = $food_model->addFood($insert_array);
            if($result){
                if($open_spec){
                    $spec_model = Model('spec');
                    $data = array(
                        'goods_id' =>$result,
                        'add_time' =>time(),
                        'type' =>3 //美食
                    );
                    foreach ($_POST['spec_sort']  as $k=>$v){
                        $data['spec_sort']   = $v;
                        $data['spec_name'] = $_POST['spec_name'][$k];
                        $data['label'] = $_POST['spec_label'][$k];
                        $data['market_price'] = $_POST['spec_market_price'][$k];
                        $data['price'] = $_POST['spec_price'][$k];
                        $data['cost_price'] = $_POST['cost_price'][$k];
                        $data['stock'] = $_POST['spec_stock'][$k];
                        $data['is_show'] = $_POST['spec_is_show'][$k];
                        $spec_model->addSpec($data);
                    }
                }
                $this->log('添加美食成功'.'[标题:'.$_POST['title'].']',1);
                showMessage(L('nc_common_save_succ'),'index.php?act=food&action=index');
            }else{
                showMessage(L('nc_common_save_fail'));
            }
        }
        $cate = $ticket_category->getCategoryList(array('tc_pid'=>FOOD_MARK,'is_del'=>0));//获取美食分类
        $provinces = $area_model->getAreaList(array('parent_id'=>1));
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }
        Tpl::output('merchants',$merchants);
        Tpl::output('provinces',$provinces);
        Tpl::output('cate',$cate);
        Tpl::output('top_link',$this->sublink($this->links,'add'));
        Tpl::showpage('food.add');
    }

    //修改页
    public function editOp(){
        $food_model = Model('food');
        /* @var areaModel $area_model */
        $area_model = Model('area');
        $id = intval($_GET['id']);
        $condition = array();
        $condition['fd_id'] = $id;
        $info = $food_model->getFoodInfo($condition);
        $info['fd_thumb'] = UPLOAD . 'food/' . $info['fd_thumb'];
        $ticket_category = Model('ticket_category');
        $cate = $ticket_category->getCategoryList(array('tc_pid'=>FOOD_MARK,'is_del'=>0));//获取美食分类
        $merchant_model = Model('member_merchant');
        $spec_model = Model('spec');
        //商家
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }
       //获取已经选中市、县
        $citys = $area_model->getAreaList(array('parent_id'=>$info['fd_province_id']));
        $areas = $area_model->getAreaList(array('parent_id'=>$info['fd_city_id']));
        $provinces = $area_model->getAreaList(array('parent_id'=>1));
        if(chksubmit()){
            $food_model = Model('food');
            $insert_array = array();

            $insert_array['fd_title'] = trim($_POST['title']);
            $insert_array['merchant_id'] = intval($this->admin_info['merchant_id'])>0?intval($this->admin_info['merchant_id']):intval($_POST['merchant_id']);
            $insert_array['cate_id'] = intval($_POST['cate1']);
            $open_spec = getgpc("open_spec");
            $obj_validate = new Validate();
            $fd_type = $_POST['food_type'];
            if($fd_type==1){
                $open_spec = 0 ;
            }

            if(!$open_spec){
                $obj_validate->validateparam = array(
                    array("input"=>$_POST["show_price"], "require"=>"true",  "message"=>'原价不能为空'),
                    array("input"=>$_POST["price"], "require"=>"true", 'min'=>0,  "message"=>'价格不能为空'),
                    array("input"=>$_POST["stock"], "require"=>"true",  "message"=>'库存不能为空'),
                    array("input"=>$_POST["label"], "require"=>"true",  "message"=>'标签不能为空'),
                );
                $error = $obj_validate->validate();
                if ($error != ''){
                    showMessage($error);
                }
                $insert_array['fd_market_price'] = floatval($_POST['show_price']);
                $insert_array['price'] = floatval($_POST['price']);
                $insert_array['stock'] = $_POST['stock'];
                $insert_array['label'] = $_POST['label'];
            }
            $insert_array['open_spec'] = $open_spec;
//            $insert_array['fd_market_price'] = floatval($_POST['show_price']);
//            $insert_array['price'] = floatval($_POST['price']);
//            $insert_array['stock'] = $_POST['stock'];
//            $insert_array['label'] = $_POST['label'];
            $insert_array['fd_content'] = $_POST['content'];//菜品介绍
            $insert_array['fd_tips']    = $_POST['content1'];//购买需知
            $insert_array['fd_subtitle'] = $_POST['fd_subtitle'];//副标题
            $insert_array['cost_price'] = $_POST['cost_price_'];
            $insert_array['fd_update_time'] = time();
            $insert_array['fd_type'] = $_POST['food_type'];
            $insert_array['deduction'] = $_POST['deduction'];
            $insert_array['sales'] = intval($_POST['sales']);
            //地址
            $store_location = trim($_POST['store_location']);
            $store_gps = explode(',', $store_location);
            $insert_array['food_lat']   = $store_gps[1];
            $insert_array['food_lng']   = $store_gps[0];
            $insert_array['fd_province_id'] = $_POST['province_id'];
            $insert_array['fd_city_id'] =$_POST['city_id'];
            $insert_array['fd_area_id'] =$_POST['area_id'];
            $insert_array['fd_addr'] = $_POST['addr'];
            $insert_array['fd_city_name'] = $area_model->getfby_area_id($_POST['city_id'],'name');
            $insert_array['fd_full_addr'] = implode('',array(
                $area_model->getfby_area_id(intval($_POST['province_id']),'name'),
                $insert_array['fd_city_name'],
                $area_model->getfby_area_id(intval($_POST['area_id']),'name'),
                $_POST['addr']
            ));
            //var_dump($insert_array['fd_full_addr']);exit;
            $insert_array['is_purchase'] = intval(getgpc('is_purchase'));//是否可购买
            if($_FILES['thumb']['tmp_name']){
                $upload = new UploadFile();
                $upload->set('default_dir','food/'.$upload->getSysSetPath());
                $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
                $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
                $upload->set('thumb_ext', GOODS_IMAGES_EXT);
                $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
                //封面图片
                $result = $upload->upfile('thumb');
                if($result){
                    $insert_array['fd_thumb'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log('酒店封面图上传失败'.'[标题:'.$_POST['title'].']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            if($open_spec){
                $insert_array['price'] = min($_POST['spec_price']); //提取规格中的最低价 插入美食表中
                $key = array_search(min($_POST['spec_price']),$_POST['spec_price']);
                $insert_array['fd_market_price'] = $_POST['spec_market_price'][$key]; //提取规格中最低价的展示价 插入美食表中
            }

            $result = $food_model->updateFood(array('fd_id'=>$id),$insert_array);
            if($result){
                if($open_spec){
                    foreach ($_POST['spec_sort']  as $k=>$v){
                        $data['spec_sort']   = $v;
                        $spec_id = $_POST['spec_id'][$k];
                        $data['spec_name'] = $_POST['spec_name'][$k];
                        $data['label'] = $_POST['spec_label'][$k];
                        $data['market_price'] = $_POST['spec_market_price'][$k];
                        $data['cost_price'] = $_POST['cost_price'][$k];
                        $data['price'] = $_POST['spec_price'][$k];
                        $data['stock'] = $_POST['spec_stock'][$k];
                        $data['is_show'] = $_POST['spec_is_show'][$k];
                        $data['type']    = 3;  $data['goods_id'] = $id;
                        if(empty($spec_id)){
                            $spec_model->addSpec($data);
                        }else{
                            $spec_model->updateSpec(array('spec_id'=>$spec_id),$data);
                        }
                    }
                }
                $this->log('编辑美食成功'.'[标题:'.$_POST['title'].']',1);
                showMessage(L('nc_common_save_succ'),'index.php?act=food&action=index');
            }else{
                showMessage(L('nc_common_save_fail'));
            }
        }
        //基础信息,相册
        $sublinks = array(
            array('url'=>'act=food&op=edit&id=' . $id,'lang'=>'food_index_index'),
            array('url'=>'act=food&op=photo&id=' . $id,'lang'=>'index_photo')
        );

        $spec_list = $spec_model->getSpecListPage(array('goods_id'=>$id,'type'=>3,));
        Tpl::output('spec_list',$spec_list);
//        echo $info['open_spec']; exit();
        Tpl::output('food_info',$info);
        Tpl::output('top_link',$this->sublink($this->links,'edit'));
        Tpl::output('sub_link',$this->sublink($sublinks,'edit'));
        Tpl::output('merchants',$merchants);
        Tpl::output('cate',$cate);
        Tpl::output('citys', $citys);
        Tpl::output('areas', $areas);
        Tpl::output('provinces', $provinces);
        Tpl::showpage('food.edit');
    }

    /**
     * 相册
     */
    public function photoOp()
    {
        $tk_id = intval($_GET['id']);
        /* @var ticket_imagesModel $images_model */
        $images_model = Model('ticket_images');

        if ($_FILES) {
            $upload = new UploadFile();
            $upload->set('default_dir', 'food/' . $upload->getSysSetPath());
            $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
            $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
            $upload->set('thumb_ext', GOODS_IMAGES_EXT);
            $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
            $result = $upload->upfile('file');
            if($result){
                //得到图片上传后的路径
                $path = $upload->getSysSetPath() . $upload->file_name;
                $params = array(
                    'tk_id' => $tk_id,
                    'img_size' => round($_FILES['file']['size'] / 1024),
                    'img_ext' => $upload->ext,
                    'img_path' => $path,
                    'img_addtime' => time(),
                    'type'=>FOOD_MARK
                );
                //保存到数据库
                if ($img_id = $images_model->addTicketImage($params)) {
                    $this->log('上传美食图册'.'[tk_id:'.$tk_id.'][img_id:'.$img_id.']', 1);
                    exit(json_encode(array(
                        'res' => true,
                        'id' => $img_id,
                        'path' => UPLOAD . 'food/' . $path
                    )));
                }
            }
            $this->log(L('nc_add,ticket_index_photo').'[tk_id:'.$tk_id.']', 0);
            exit(json_encode(array('res'=>false)));
        }

        Tpl::output('tk_id', $tk_id);
        $images = $images_model->getTicketImageList(array('tk_id'=>$tk_id, 'img_deleted'=>0,'type'=>FOOD_MARK));
        foreach ($images as $k => $img) {
            $images[$k]['img_path'] = UPLOAD . 'food/' . $img['img_path'];
        }
        Tpl::output('images',$images);

        array_push($this->links, array('url'=>'act=food&op=edit&id=' . $tk_id,'lang'=>'nc_edit'));
        Tpl::output('top_link',$this->sublink($this->links,'edit'));
        //基础信息,相册
        $sublinks = array(
            array('url'=>'act=food&op=edit&id=' . $tk_id,'lang'=>'ticket_index_baseinfo'),
            array('url'=>'act=food&op=photo&id=' . $tk_id,'lang'=>'ticket_index_photo')
        );
        Tpl::output('sub_link',$this->sublink($sublinks,'photo'));
        Tpl::showpage('food.photo');
    }

    /**
     * ajax更改上架状态
     */
    public function  ajaxstatusOp()
    {
        /* @var ticketModel $ticket_model */
        $ticket_model = Model('food');

        $type = $_GET['type'];

        switch ($type) {
            case 'change_recommend':
                $tk_id = $_POST['tk_id'];
                $tk = $ticket_model->getFoodInfo(array('id'=>$tk_id));
                if ($tk) {
                    $recommend = $tk['tk_is_recommend'] ? 0 : 1;
                    $res = $ticket_model->updateHotel(array('id'=>$tk_id), array('tk_is_recommend'=>$recommend));
                    $action = $recommend ? 'ticket_add_recommend' : 'ticket_index_not_recommend';
                    $this->log(L('ticket_index_ticket,'.$action).'[id:'.$tk_id.']', $res?1:0);
                    exit(json_encode(array('res'=>$res, 'new_recommend'=>$recommend)));
                } else {
                    exit(json_encode(array('res'=>false, 'new_recommend'=>'')));
                }
            case 'change_status':
                $tk_id = $_POST['tk_id'];
                $tk = $ticket_model->getFoodInfo(array('fd_id'=>$tk_id));
                if ($tk) {
                    $status = $tk['fd_status'] ? 0 : 1;
                    $res = $ticket_model->updateFood(array('fd_id'=>$tk_id), array('fd_status'=>$status));
                    $action = $status ? 'ticket_index_show' : 'ticket_index_hide';
                    $this->log('美食'.L($action).'[tk_id:'.$tk_id.']', $res?1:0);
                    exit(json_encode(array('res'=>$res, 'new_status'=>$status)));
                } else {
                    exit(json_encode(array('res'=>false, 'new_status'=>'')));
                }
            case 'change_all':
                $ids = $_POST['ids'];
                $status = $_POST['type'] == 'show' ? 1 : 0;
                $condition = array(
                    'fd_id' => array('in', implode(',', $ids))
                );
                $res = $ticket_model->updateFood($condition, array('fd_status'=>$status));
                $action = $status ? 'ticket_index_show' : 'ticket_index_hide';
                $this->log('美食'.L($action).'[id:'.implode(',',$ids).']', $res?1:0);
                exit(json_encode(array('res'=>$res)));
        }
    }


    /**
     * 删除规格
     */
    public function delete_specOp(){
        $spec_id = getgpc('spec_id');
        if(empty($spec_id)){
            die(json_encode(array('tab' => 'error', 'info' => '参数错误')));
        }else{
            $spec_model = Model('spec');
            $rs = $spec_model->deleteSpec(array('spec_id'=>$spec_id));
            if($rs) {
                $this->log(L('nc_delete').'规格； [ID:'.intval($_POST['spec_id']).']',1);
                die(json_encode(array('tab' => 'success', 'info' => '删除成功')));
            }else{
                die(json_encode(array('tab' => 'error', 'info' => '删除失败')));
            }
        }
    }

    /**
     *  删除美食
     */
    public function del_foodOp()
    {
        $fd_id = $_POST['fd_id'];
        if($fd_id>0){
            /* @var foodModel $food_model*/
            $food_model = Model('food');
            /* @var specModel $spec_model */
            $spec_model = Model('spec');
            $fd = $food_model->getFoodInfo(array('fd_id'=>$fd_id));
            if($fd){
                $res = $food_model->deleteFood(array('fd_id'=>$fd_id));
                $res_ = $spec_model->deleteSpec(array('goods_id'=>$fd_id,'type'=>FOOD_MARK));
                if($res && $res_){
                    exit(json_encode(array('res'=>true, 'msg_'=>'成功')));
                }else{
                    exit(json_encode(array('res'=>false, 'msg_'=>'删除失败')));
                }
            }else{
                exit(json_encode(array('res'=>false, 'msg_'=>'酒店不存在')));
            }
        }
    }


}